#include"snake.h"

 void initUserSystem(){
    head=NULL;
    curentUser=NULL;
    loadUserScores();
 }

 UserNode* createUserNode(const char* id){
    UserNode* newNode=(UserNode*)malloc(sizeof(UserNode));
    if(newNode==NULL){
        printf("1 error\n");
        exit(1);
    }

    strcpy(newNode->id,id);
    newNode->score=0;
    newNode->next=NULL;
    return newNode;
 }

UserNode* findUser(const char* id) {
    UserNode* current = head;
    while (current != NULL) {
        if (strcmp(current->id, id) == 0) {
            return current;
        }
        current = current->next;
    }
    return NULL;
}

// 初始界面、登录、写入文件功能
void initUser() {
   
    system("cls"); 
    printf("================ Snake Game ================\n");

    printf("CREATE YOUR ID:");
    char id[50];
    scanf("%s",id);
    printf("\n");

    curentUser=findUser(id);
    if(curentUser==NULL){
        curentUser=createUserNode(id);
        curentUser->next=head;
        head=curentUser;
        printf("new user:%s\n",id);
    }else{
        printf("welcome back %s,your highest score:%d\n",id,curentUser->score);
    }
    
    printf("press anykey to begin game ...\n");
   
    getchar();
    getchar(); 
}

void updateUserScore(int newScore){
    if(curentUser!=NULL){
        if(newScore>curentUser->score){
            curentUser->score=newScore;
            printf("new history\n");
            saveUserScores();
        }
    }
}

void saveUserScores(){
    FILE *fp=fopen("user_scores.dat","wb");
    if(fp==NULL){
        printf("2 error\n");
        exit(1);
    }

    int count=0;
    UserNode* current=head;
    while(current!=NULL){
        count++;
        current=current->next;
    }
    fwrite(&count,sizeof(int),1,fp);

    current=head;
    while(current!=NULL){
        fwrite(current->id,sizeof(char),50,fp);
        fwrite(&current->score,sizeof(int),1,fp);
        current=current->next;
    }

    fclose(fp);
}

void loadUserScores(){
    FILE *fp=fopen("user_scores.dat","rb");
    if(fp==NULL){
        printf("6 error\n");
        return;
    }

    while(head!=NULL){
        UserNode* temp=head;
        head=head->next;
        free(temp);
    }

    int count;
    fread(&count,sizeof(int),1,fp);

    for(int i=0; i<count; i++){
        UserNode* newNode=(UserNode*)malloc(sizeof(UserNode));
        if(newNode==NULL){
            printf("3 error\n");
            fclose(fp);
            exit(1);
        }

        fread(newNode->id,sizeof(char),50,fp);
        fread(&newNode->score,sizeof(int),1,fp);
        newNode->next=head;
        head=newNode;
    }

    fclose(fp);
}

void showScoreRanking(){
    system("cls");

    if(head == NULL){
        printf("can not recieve users' info\n");
        printf("press any key to return...\n");
        while(getchar() != '\n'); // 清除可能的残留输入
        getchar(); // 等待用户按键
        return;
    }

    // 创建临时链表进行排序
    UserNode* tempHead = NULL;
    UserNode* current = head;

    while(current != NULL){
        UserNode* newNode = (UserNode*)malloc(sizeof(UserNode));
        if(newNode == NULL){
            printf("4 error\n");
            exit(1);
        }

        strcpy(newNode->id, current->id);
        newNode->score = current->score;
        newNode->next = tempHead; 
        tempHead = newNode;
        current = current->next;
    }

    // 冒泡排序
    int swapped;
    do{
        swapped = 0;
        current = tempHead;
        while(current != NULL && current->next != NULL){
            if(current->score < current->next->score){
                char tempid[50];
                int tempscore;
                strcpy(tempid, current->id);
                tempscore = current->score;
                strcpy(current->id, current->next->id);
                current->score = current->next->score;
                strcpy(current->next->id, tempid);
                current->next->score = tempscore;
                swapped = 1;
            }
            current = current->next;
        }
    }while(swapped);

    // 显示排名
    printf("====== Score Ranking ======\n");
    int rank = 1;
    current = tempHead;
    while(current != NULL && rank <= 10){
        printf("%d. %-10s %d\n", rank, current->id, current->score);
        current = current->next;
        rank++;
    }

    printf("\npress any key to return...\n");
    
    // 改进的输入处理：清除缓冲区并等待用户按键
    while(getchar() != '\n'); // 清除可能的残留输入
    getchar(); // 等待用户按键

    while(tempHead != NULL){
        UserNode* temp = tempHead;
        tempHead = tempHead->next;
        free(temp);
    }
}

void gameOver(){
    system("cls");

    printf("======Game Over======\n");
    printf("YOUR SCORE:%d\n",game.score);

    if(curentUser!=NULL){
        updateUserScore(game.score);
    }

    printf("press 1 to check the ranking or else to exit\n");
    
    // 读取用户输入
    char key = getchar();
    while(getchar() != '\n'); 

    if(key == '1'){
        showScoreRanking();
    }
}